package com.dpf.api.utills;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/*加解密*/
@Slf4j
public final class EncryptUtils {

    //region 3DesECB模式
    //获取3des加密key
    public static byte[] Build3DESKey(String encryptionKey) {
        byte[] key = encryptionKey.getBytes(StandardCharsets.UTF_8);

        byte[] temp = new byte[24];
        System.arraycopy(key, 0, temp, 0, Math.min(key.length, temp.length));
        return temp;
    }

    //加密
    public static String encode3DES(String message, String keyString) {
        String result;   //DES加密字符串
        try {
            SecretKey secretKey = new SecretKeySpec(Build3DESKey(keyString), "DESede");//获得密钥
            /*获得一个私鈅加密类Cipher，DESede是算法，ECB是加密模式，PKCS5Padding是填充方式*/
            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);     //设置工作模式为加密模式，给出密钥
            byte[] resultBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8)); //正式执行加密操作
            Base64.Encoder enc = Base64.getEncoder();
            result = new String(enc.encode(resultBytes));//进行BASE64编码
            //去掉加密串中的换行符
            result = result.replaceAll("[\\r\\n]", "");
        } catch (Exception e) {
            return e.getMessage();
        }
        return result;
    }

    //解密
    public static String decode3DesECB(String message, String keyString){
        String result = "";
        try {
            SecretKey secretKey = new SecretKeySpec(Build3DESKey(keyString), "DESede");//获得密钥
            Base64.Decoder dec = Base64.getDecoder();
            byte[] messageBytes = dec.decode(message);  //进行BASE64编码
            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);      //设置工作模式为解密模式，给出密钥
            byte[] resultBytes = cipher.doFinal(messageBytes);//正式执行解密操作
            result = new String(resultBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("系统异常",e);
            e.printStackTrace();
        }
        return result;
    }
    //endregion

    public static String hmacsha1String(String str, String key) {
        try {
            byte[] bytesStr = str.getBytes(StandardCharsets.UTF_8);
            byte[] bytesKey = key.getBytes(StandardCharsets.UTF_8);
            return hmacsha1(bytesStr, bytesKey);
        } catch (Exception ex) {
            return "";
        }

    }


    public static String hmacsha1(byte[] data, byte[] key) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            return byte2hex(mac.doFinal(data));
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("系统异常",e);
            e.printStackTrace();
        }
        return null;
    }

    //二行制转字符串
    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    public static void main(String[] args) {
        String phones="19811111129";
        String phone_encode=encode3DES(phones,"!QAZ@WSX3edc4rfv5tjtkgflHFkTj@%");
        System.out.println(phone_encode);
        String phone_decode=decode3DesECB("QgJmq9oLuHXt7y8tPmxmGw==","!QAZ@WSX3edc4rfv5tjtkgflHFkTj@%");
        System.out.println(phone_decode);

    }
}
